package cn.zfs.springcloud.datasource.config;

import cn.zfs.springcloud.datasource.DynamicDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings({"JavaDoc", "unchecked", "SpringFacetCodeInspection"})
@Configuration
public class DataSourceConfig{

    @Qualifier
    @Bean(name = "db_master")
    @ConfigurationProperties(prefix = "db_master") // application.properteis中对应属性的前缀
    public DataSource dbMaster() {
        return DataSourceBuilder.create().build();
    }

    @Qualifier
    @Bean(name = "db_dev")
    @ConfigurationProperties(prefix = "db_dev") // application.properteis中对应属性的前缀
    public DataSource dbDev() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 动态数据源: 通过AOP在不同数据源之间动态切换
     *
     * @return
     */
    @Primary
    @Qualifier
    @Bean(name = "dataSource")
    public DataSource dataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        // 默认数据源
        dynamicDataSource.setDefaultTargetDataSource(dbMaster());
        // 配置多数据源
        Map<Object, Object> dsMap = new HashMap(5);
        dsMap.put("db_master", dbMaster());
        dsMap.put("db_dev", dbDev());
        dynamicDataSource.setTargetDataSources(dsMap);
        return dynamicDataSource;
    }
}